<template>
	<div>
		<van-nav-bar title="提交订单" left-text="" left-arrow @click-left="booking" />
		<van-cell-group>
			<!-- 选择服务 -->
			<van-field v-model="forma.listofserveId" label="添加服务地址" placeholder="请填写服务地址" required is-link readonly
				@click="onSelectServiceType" />


      <!-- 选择预约时间 -->
      <van-field v-model="forma.orderBegintime" label="预约时间" placeholder="请选择" required is-link readonly
                 @click="onSelectAppointmentTime" />
			<!-- 出行方式 -->
      <van-radio-group v-model="checkedes" direction="horizontal">
        出行方式:
        <van-radio  v-model="forma.around" name="1">公交</van-radio>
        <van-radio  v-model="forma.around" name="2">滴滴出行</van-radio>
      </van-radio-group>

      <van-field v-model="forma.cid" label="优惠券" placeholder="请选择" required is-link readonly
                 @click="onSelectDoctor" />
      <van-field v-model="forma.amountOrDiscount" label="优惠价格" placeholder="请选择" required is-link readonly
                 @click="onSelectDoctor" />

      <!--      账户余额支付-->
      <van-radio-group v-model="checked">
        <van-cell-group inset>
          <van-cell title="账户余额支付"   clickable @click="checked = '1'">
            <template #right-icon >
              <van-radio name="1"  v-model="forma.payments"/>
            </template>
          </van-cell>
          <van-cell title="微信支付" v-model="forma.payments" clickable @click="checked = '2'">
            <template #right-icon>
              <van-radio name="2" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>

    </van-cell-group>


      <van-field v-model="forma.remark" label="备注" type="textarea" placeholder="请详细描述" rows="3" />
			<!-- 选择陪诊师 -->

      <div v-for="(value, index) in fan" :key="index" class="order-details">
        <!-- 图片和内容部分 -->
        <div class="order-info-content">
          <!-- 左侧图片 -->
          <div class="order-image">
            <img :src="value.photo" alt="Item Image"/>
          </div>
          <!-- 右侧内容 -->
          <div class="order-text">
            <span class="title">{{ value.name }}</span>
            <van-tag type="success" round>{{value.effect}}</van-tag>

            <span class="hospital" style="color: red;font-size: 20px">{{ value.price}}元</span>
            <span class="hospital">{{ value.minutes}}分钟</span>
            <span class="hospital">已有:{{ value.choose}}人选择</span>
          </div>

        </div>
        <div class="order-footer">
          <div class="order-price">
            <span class="price-labels" >合计:<span style="color: red;font-size: 20px">￥{{form.finalPrice}}.00</span></span>
          </div>
          <button class="accept-btns"  @click="paycont()">立即支付</button>
        </div>


      </div>
	</div>

</template>
<script>
	import axios from 'axios';
  import { ref } from 'vue';
  import { VanRadio, VanRadioGroup } from 'vant';

	export default {
		data() {
			return {
        cid: null,
        amountOrDiscount: 0,
        originalPrice: 0,
        checked: '1',
        checkedes:'1',
				active: 3,
				fwlbId: "",
				form: {},
				forma: {},
				value: '',
				//   往后端传递的id
				order: {},
				user: {},
        fan:{
          price:"",
        },
        tids:[],
        Sum:{},
        jinqian:{},
        couid:null,
			}
		},
		created() {
      this.forma.orderBegintime = sessionStorage.getItem("createTime")
      // this.forma.userEscortid=sessionStorage.getItem("coupon","couponName")
      // this.tids=this.$route.query.tids;
      this.tids=sessionStorage.getItem("tidInfo")
        // alert(this.tids+"----------------------------------")
      console.log(this.tids)
      this.findPage();
			var item = sessionStorage.getItem("userDB");
			if (item == null) {
				location.href = "#/login";
			}
			this.user = JSON.parse(item);
      // 取session域中address的数据
      let addressString = sessionStorage.getItem("address");
      if (addressString) {
        let address = JSON.parse(addressString);
        let one = address.contactName;
        let two = address.contactPhone;
        let three = address.detailAddress;
        // 显示订单信息
        this.forma.listofserveId = one+" "+two+" "+three;
      }
      // 取session域中coupon的数据
      let couponString = sessionStorage.getItem("coupon");
      if (couponString) {
        let coupon = JSON.parse(couponString);
        console.log("Coupon object:", coupon); // 添加调试信息
        if (coupon && coupon.amountOrDiscount !== undefined) {
          this.forma.cid = coupon.couponName;
          this.forma.amountOrDiscount = parseFloat(coupon.amountOrDiscount); // 确保是数值类型
        } else {
          console.error("Coupon does not have 'amountOrDiscount' property"); // 添加调试信息
          this.forma.cid = null;
          this.forma.amountOrDiscount = 0; // 设置默认值
        }
      } else {
        // 处理 coupon 不存在的情况
        this.forma.cid = null;
        this.forma.amountOrDiscount = 0; // 设置默认值
      }

      // 计算最终价格
      this.calculateFinalPrice();
      this.getUserFromSession();
		},
		methods: {
      submitOrder() {
        // 检查余额是否足够
        if (this.item.accountBalance >= this.qianed) {
          // 执行支付逻辑
          this.deductBalance(this.form.finalPrice);
        } else {
          this.paymentResult = '余额不足，请充值后再试！';
        }
      },
      deductBalance(amount) {
        // 扣款逻辑
        this.item.accountBalance -= amount;
        // 更新sessionStorage中的用户信息
        sessionStorage.setItem('userDB', JSON.stringify(this.userDB));
        this.paymentResult = '支付成功！';
      },
      getUserFromSession() {
        // 从sessionStorage中获取用户信息
        const userData = sessionStorage.getItem('userDB');
        console.log(userData+"00000000000000000")
        if (userData) {
          try {
            // 将字符串转换为JavaScript对象
            this.userDB = JSON.parse(userData);
          } catch (error) {
            console.error('解析用户数据时出错:', error);
          }
        } else {
          console.log('sessionStorage中没有找到用户信息');
        }
      },
      paycont() {
        // 确保 userDB 已经被正确赋值
        if (this.userDB && this.userDB.accountBalance) {
          let zong = this.userDB.accountBalance;
          console.log(zong + "总共的钱");
          console.log(this.form.finalPrice + "优惠之后的钱");

          // 判断金额是否足够
          if (zong >= this.form.finalPrice) {
            // 扣款逻辑
            let remainingBalance = zong - this.form.finalPrice;
            // 发送请求到后端进行扣款
            this.jinqian.id=this.user.id;
            console.log(this.jinqian.id+"用户id============================================")
            this.jinqian.accountBalance=remainingBalance;
            console.log(this.jinqian.accountBalance+"金钱============================================")
            axios.post(`http://localhost:10086/technician/UpdatePrice`, this.jinqian).then(res => {
              if (res.data.code==200) {
                // 扣款成功，更新前端状态
                this.userDB.accountBalance = remainingBalance;
                sessionStorage.setItem('userDB', JSON.stringify(this.userDB));
               this.$message.success("支付成功");


               let coupay=sessionStorage.getItem("coupon");
               this.couid=JSON.parse(coupay).couponId;
               console.log(this.couid+"优惠券id============================================")
                axios.post(`http://localhost:10086/technician/updateCouponStatus/${this.couid}`).then(res => {
                  console.log(res.data+"优惠券状态修改返回码============================================")
                  if (res.data==1) {
                    this.$message.success("优惠券状态修改成功");
                  } else {
                    this.$message.error("优惠券状态修改失败");
                  }
})
                this.$router.replace({ path: '/yuyue' });
              } else {
                // 扣款失败
                alert("支付失败，请重试！");
              }
            }).catch(error => {
              // console.error("扣款请求失败:", error);
              this.$message.error("扣款失败",error);
              alert("支付失败，请重试！");
            });
          } else {
           this.$message.error("余额不足，请充值后再试！");
          }
        } else {
          console.error('userDB 或 accountBalance 未定义');
          this.$message.error("用户信息未找到，请重新登录！");
          // alert("用户信息未找到，请重新登录！");
        }

      },
      calculateFinalPrice() {
        let originalPrice = sessionStorage.getItem("qian"); // 原始价格
        console.log("原始价格:", originalPrice)
        let couponValue = this.forma.amountOrDiscount || 0; // 使用 amountOrDiscount 作为优惠券金额
        this.form.finalPrice = originalPrice - couponValue; // 最终价格
      },
      findPage() {
        console.log("技术员id======" + this.tids)
        axios.post(`http://localhost:10086/technician/selectOrder?id=${this.tids}`).then(res => {
          this.fan = res.data;
        })
      },
			booking() {
				this.$router.push('/fu');
			},

			onSelectServiceType() {
				this.$router.push('/address');
			},

			onSelectHospital() {
				this.$router.push('/selectHospital');
			},

			onSelectDepartment() {
				this.$router.push('/selectDepartment');
			},

			onSelectDoctor() {
				this.$router.push('/youhuijuan');
			},

			onSelectAppointmentTime() {
				this.$router.push('/selectTime');
			},

			onInputPatient() {
				this.$router.push('/selectInputPatient');
			},
			//提交订单

			submitAppointment() {

				// 服务id
				this.order.listofserveId = this.form.fwid
				this.order.hospitalId = this.form.yyid
				this.order.departmentId = this.form.ksid
				this.order.cid = this.form.pzsid
				this.order.orderBegintime = this.form.createTime
				this.order.orderEndtime = this.form.endtime
				this.order.userRescuers = this.form.rescuer
				this.order.remark = this.form.remark
				this.order.orderMoney = this.form.orderMoney
				this.order.orderIncome = this.form.orderIncome
				this.order.cityId = this.form.cityId
				this.order.usid = this.user.id

				axios.post("http://123.56.135.19:5432/api-user-homepage/homepage/addOrder", this.order).then(res => {
					if (res.data.data == 1) {
						this.$toast('预约成功');

					} else {
						this.$toast('预约失败');
					}
				})
				this.form = {}
				this.forma = {}
				this.form.fwid = sessionStorage.setItem('fwid', '')
				this.forma.listofserveId = sessionStorage.setItem('fwname', '')
				this.form.yyid = sessionStorage.setItem('yyid', '')
				this.forma.hospitalId = sessionStorage.setItem('yyname', '')
				this.form.ksid = sessionStorage.setItem("ksid", '')
				this.forma.departmentId = sessionStorage.setItem("ksname", '')
				this.form.pzsid = sessionStorage.setItem("pzsid", '')
				this.forma.cid = sessionStorage.setItem("pzsname", '')
				this.form.createTime = sessionStorage.setItem("createTime", '')
				this.forma.orderBegintime = sessionStorage.setItem("createTime", '')
				this.form.endtime = sessionStorage.setItem("endTime", '')
				this.form.rescuer = sessionStorage.setItem("rescuerid", '')
				this.forma.userRescuers = sessionStorage.setItem("rescuername", '')
				this.form.orderMoney = sessionStorage.setItem("fwmoney", '')
				this.form.cityId = sessionStorage.setItem("yycity", '')


				setTimeout(() => {
					this.$router.push('/patient');
				}, 500);


				//
			}


		},
	}
</script>

<style>
.price-labels{
  float:left;
  margin-right: 200px;
}
.accept-btns{
  width: 80px;
  height: 35px;
  float: right;
color: white;
  background-color: #4fc08d;
  border-bottom-left-radius: 10px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;

}
</style>